const chalk = require('chalk');
const axios = require('axios');
// const http = require('http');
const fs = require('fs');

const {login} = require('./login');

const WEBROOT_PATH = './fileDown/webroot'
const FILE_SAVE_PATH = './fileDown/webroot/web/fileSave'

const HOSTPREFIX = 'http://172.19.196.155:2902';
const TASKINTERVAL = 5;
const WGGL_PREFIX = 'http://172.19.141.129:8189'

var SESSIONID = '04EF3D0350E5D30ECD6F992D34FED4096';
try {
  var newToken = fs.readFileSync('./token.txt', 'utf8');
  console.log('读取到最新的token:' + newToken);
  SESSIONID = newToken;
} catch(e) {
  console.log('没有获取token记录');
}

function getAndLoad(name, url) {
  return new Promise(resolve => {
    axios.get(HOSTPREFIX + url)
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        console.log('接口调用失败:' + name);
      });
  })
}

async function sleepWait(secend) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, secend * 1000)
  })
}


function downloadFile(url, pathName) {
  return new Promise((resolve, reject) => {
    console.log('准备下载文件：' + HOSTPREFIX + url);
    axios({
      url: HOSTPREFIX + url,
      method: 'GET',
      headers: {
        cookie: 'JSESSIONID=' + SESSIONID,
      },
      responseType: 'stream',
    }).then(response => {
      if (response.status === 200) {
        if (response.headers['content-type'].startsWith('text/html')) {
          console.log(chalk.red('需要登录, 请等待登录'));
          reject('login');
        } else {
          const contentDisposition = response.headers['content-disposition'];
          let fileName = pathName; // 默认文件名
          fs.mkdirSync(pathName, { recursive: true });
          if (contentDisposition) {
            var name = decodeURIComponent(contentDisposition.split('filename=')[1]);
            name = name.replace(/[\\\/:*?"<>|\n\s]/g, '');
            if (name.endsWith('.zip')) {
              name = 'download.zip';
            }
            fileName = fileName + name;
          } else {
            fileName = fileName + 'unknowname.pdf'
          }
          const fileStream = fs.createWriteStream(fileName);
          response.data.pipe(fileStream);
          fileStream.on('finish', () => {
            fileName = fileName.replace(WEBROOT_PATH, '');
            console.log(`${chalk.green('文件下载完成：')} ${fileName}`);
            fileStream.close();
            resolve(fileName);
          });
          fileStream.on('error', (err) => {
            fs.unlinkSync(fileName); // 删除错误创建的文件
            console.log(chalk.red('文件存储失败', err.message));
            reject();
          });
        }
      }
    }).catch(e => {
      reject(e);
    }) ;
  });

}

async function doLogin() {
  return new Promise(resolve => {
    login().then(session => {
      SESSIONID = session;
      fs.writeFileSync('./token.txt', session);
      console.log('获取会话成功!');
      resolve();
    }).catch(e => {
      console.log(chalk.red('登录失败, 3秒后重试'));
      setTimeout(() => {
        return doLogin();
      }, 3000)
    })
  })
}

function doLogo(str) {
  fs.appendFileSync('./log.txt', str, 'utf8');
}
function postToWggl(filePath, gwInfo, receiveId) {
  var json = {
    "userName":"13605129298",//用户登录名
    "password":"Gnzhzx@0518",//密码
    "data":{
      "deptName":"",
      "receiveId":receiveId,
      "title": gwInfo.title,
      "mainNote":"",
      "attach":""
    }
  }
  if (filePath.endsWith('pdf') || filePath.endsWith('doc') || filePath.endsWith('docx') || filePath.endsWith('xls') || filePath.endsWith('xlsx')) {
    json.data.mainNote = filePath;
  } else {
    json.data.attach = filePath;
  }
  var api = `${WGGL_PREFIX}/websites/login/mobileLogin/api/otherLogin.jsp`;
  return axios.post(api, json, { 'content-type': 'application/json' });
}

async function testPost () {
  var info = {"title":"关于组织开展灌南县第九期“与理分享”云课堂直播活动的\n                       通知","link":"http://172.19.196.155:2902/trueWorkFlow/table_openReceiveForm.do?receiveId=A8A0D9E9-0CAB-4C52-8EC6-5FBE065D5E29&jrdb=true&status=0","cate":"快速发文","date":"2024-03-28 17:45","isnew":"0","imgPath":"","processId":"5D01DD1C-E546-4A93-B032-B7C0311B0526"};
  var receiveId = 'A8A0D9E9-0CAB-4C52-8EC6-5FBE065D5E29';
  var path = './fileDown/202442162522-关于上传省委巡视反馈系统录入要求的通知.pdf';
  var response = await postToWggl(path, info, receiveId);
  console.log(response.data);
}

async function doSingTask(gwInfo) {
  try {
    var title = gwInfo.title;
    var link = gwInfo.link;

    var url = new URL(link);
    var params = new URLSearchParams(url.search);
    var receiveId = params.get('receiveId');
    var jrdb = params.get('jrdb');

    // 文书下载
    var file_download_link = '/trueWorkFlow/table_downloadTure.do?receiveId=' + receiveId + '&name=' + encodeURIComponent(title);

    var filePath = await downloadFile(file_download_link, getFilePathName());
    var response = await axios.post(HOSTPREFIX + `/trueWorkFlow/table_updateDoFileReceive.do`, 
    { 'id' : receiveId, 'jrdb': jrdb, 'state': '0' },
    { 
      headers: { cookie: 'JSESSIONID=' + SESSIONID, 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    var result = response.data;
    if (result == 'yes') { //收取成功
      console.log(chalk.green('公文自动签收成功!') + '----' + title);
      var postRes = await postToWggl(filePath, gwInfo, receiveId);
      var postData = postRes.data && postRes.data.data ? JSON.stringify(postRes.data.data) : postRes.data;
      console.log(postData);
      doLogo(`【成功签收】: ${new Date().toLocaleString()}\n${JSON.stringify(gwInfo)}\n公文下载路径：${filePath}\n提交后台结果:${postData}\n-----------------------\n`);
      return {filePath, gwInfo, receiveId}
    } else if(result == 'over'){
      var postRes = await postToWggl(filePath, gwInfo, receiveId);
      var postData = postRes.data && postRes.data.data ? JSON.stringify(postRes.data.data) : postRes.data;
      console.log(postData);
      doLogo(`【非脚本签收，但轮训时未签收】: ${new Date().toLocaleString()}\n${JSON.stringify(gwInfo)}\n公文下载路径：${filePath}\n提交后台结果:${postData}\n-----------------------\n`);
      console.log(chalk.red('公文已经被其他用户签收!') + '----' + title);
    }else{
      doLogo(`【签收失败】: ${new Date().toLocaleString()}\n${JSON.stringify(gwInfo)}\n公文下载路径：${filePath}\n-----------------------\n`);
      console.log(chalk.red('公文自动签收失败!') + '----' + chalk.blue(JSON.stringify(result)) + title);
    }
  } catch(e) {
    if (e == 'login') {
      await doLogin();
      await doSingTask(gwInfo)
    }
  }

}

async function mainFoo() {

  var dqsData = await getAndLoad('待签收列表', '/trueWorkFlow/eworkflow_searchByStatus.do?colunm=0&pagesize=10&status=7&userId=2b053d2f-17e5-4ea4-8b74-ef66ef5aa7f3');
  try {
    dqsData = JSON.parse(dqsData = dqsData.slice(1, -1));
  } catch (e) {
    console.log('待签收列表获取失败');
  }
  var doSingNum = dqsData.data.num;
  if (doSingNum) {
    console.log(`有` + chalk.red(doSingNum) + `条待签收公文`);
    var gwInfo = dqsData.data.content[0];
    console.log(`准备签收公文：` + JSON.stringify(gwInfo));
    await doSingTask(gwInfo);
  } else {
    console.log(`没有待签收公文, ${TASKINTERVAL}秒后再次检查`);
    await sleepWait(TASKINTERVAL)
  }
  await mainFoo();
}



// 测试签收
async function testSign () {
  var info = {"title":"关于组织开展灌南县第九期“与理分享”云课堂直播活动的\n                       通知","link":"http://172.19.196.155:2902/trueWorkFlow/table_openReceiveForm.do?receiveId=A8A0D9E9-0CAB-4C52-8EC6-5FBE065D5E29&jrdb=true&status=0","cate":"快速发文","date":"2024-03-28 17:45","isnew":"0","imgPath":"","processId":"5D01DD1C-E546-4A93-B032-B7C0311B0526"};
  // var info = {"title":"灌南县12345在线工作日报第84期（总1309期）3.24","link":"http://172.19.196.155:2902/trueWorkFlow/table_openReceiveForm.do?receiveId=C2F29DD0-4C47-4620-8B78-03438F960D58&jrdb=true&status=0","cate":"灌南县政府办文单","date":"2024-03-28 16:46","isnew":"0","imgPath":"","processId":"A5A85DED-E5CB-432C-938D-CA36ABBA9483"};
  await doSingTask(info);
}

async function testMainFoo() {
  var random = Math.random();  
  if (random > 0.8) {
    console.log(`有` + chalk.red(1) + `条待签收公文`);
    await testSign();
    console.log('签收方法已执行');
  } else {
    console.log(`没有待签收公文, ${TASKINTERVAL}秒后再次检查`);
    await sleepWait(TASKINTERVAL)
  }
  await testMainFoo();
}



function getFilePathName () {
  var arr = new Date().toISOString().replace(/[\/|\s|:|-]/g, '').split('T')
  return FILE_SAVE_PATH + '/' + arr[0] + '/' + arr[1].split('.')[0] + '/';
}



// 测试下载文书
async function testDownLoad() {
  var pathName = getFilePathName();
  try {
    // await downloadFile('/trueWorkFlow/table_downloadTure.do?receiveId=01F4D272-DD6D-4473-9D17-81FE22FDCF60&name=%E5%85%B3%E4%BA%8E%E4%B8%8A%E4%BC%A0%E7%9C%81%E5%A7%94%E5%B7%A1%E8%A7%86%E5%8F%8D%E9%A6%88%E7%B3%BB%E7%BB%9F%E5%BD%95%E5%85%A5%E8%A6%81%E6%B1%82%E7%9A%84%E9%80%9A%E7%9F%A5', pathName);
    await downloadFile('/trueWorkFlow/table_downloadTure.do?receiveId=73A5095F-75AE-4BE5-A070-9DB8A8489BB9&name=%E5%85%B3%E4%BA%8E%E4%B8%8A%E4%BC%A0%E7%9C%81%E5%A7%94%E5%B7%A1%E8%A7%86%E5%8F%8D%E9%A6%88%E7%B3%BB%E7%BB%9F%E5%BD%95%E5%85%A5%E8%A6%81%E6%B1%82%E7%9A%84%E9%80%9A%E7%9F%A5', pathName);
  } catch(e) {
    if (e == 'login') {
      await doLogin();
      testDownLoad();
    }
  }
}



(async function main() {
  // testMainFoo();
  // testDownLoad();
  mainFoo();
})();

